# -*- coding: utf-8 -*-
"""
特殊功能标签页
提供节假日、农历等特殊功能
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QGridLayout,
                            QLabel, QTextEdit, QGroupBox, QFrame, QPushButton,
                            QDateEdit, QSpinBox, QComboBox, QCheckBox, QMessageBox,
                            QApplication)
from PyQt5.QtCore import Qt, QDate
from PyQt5.QtGui import QFont

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from core.lunar_calendar import LunarCalendar


class SpecialFunctionsTab(QWidget):
    """特殊功能标签页"""
    
    def __init__(self, history_manager=None):
        super().__init__()
        self.lunar_calendar = LunarCalendar()
        self.history_manager = history_manager
        self.init_ui()
    
    def init_ui(self):
        """初始化用户界面"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)
        
        # 创建水平分割布局
        content_layout = QHBoxLayout()
        content_layout.setSpacing(25)
        
        # 左侧：输入和控制区域
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(20)
        
        # 阳历转农历区域
        solar_to_lunar_group = self.create_solar_to_lunar_group()
        left_layout.addWidget(solar_to_lunar_group)
        
        # 农历转阳历区域
        lunar_to_solar_group = self.create_lunar_to_solar_group()
        left_layout.addWidget(lunar_to_solar_group)
        
        left_layout.addStretch()
        
        # 右侧：结果显示区域
        result_group = self.create_result_group()
        
        # 设置左右比例 (左侧40%，右侧60%)
        content_layout.addWidget(left_widget, 2)  # 左侧占2份
        content_layout.addWidget(result_group, 3)  # 右侧占3份
        
        main_layout.addLayout(content_layout)
    
    def create_solar_to_lunar_group(self):
        """创建阳历转农历区域"""
        group_box = QGroupBox("阳历转农历")
        group_box.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        group_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #dee2e6;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 8px 0 8px;
                color: #495057;
                background-color: #ffffff;
            }
        """)
        
        layout = QGridLayout(group_box)
        layout.setSpacing(15)
        layout.setContentsMargins(25, 30, 25, 25)
        
        # 阳历日期选择
        layout.addWidget(QLabel("阳历日期:"), 0, 0)
        self.solar_date_edit = QDateEdit()
        self.solar_date_edit.setDate(QDate.currentDate())
        self.solar_date_edit.setCalendarPopup(True)
        self.solar_date_edit.setDisplayFormat("yyyy年MM月dd日")
        self.solar_date_edit.setMinimumHeight(30)
        layout.addWidget(self.solar_date_edit, 0, 1)
        
        # 转换按钮
        solar_convert_btn = QPushButton("转换为农历")
        solar_convert_btn.setMinimumHeight(35)
        solar_convert_btn.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 12px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #1e7e34;
            }
        """)
        solar_convert_btn.clicked.connect(self.convert_solar_to_lunar)
        layout.addWidget(solar_convert_btn, 0, 2)
        
        return group_box
    
    def create_lunar_to_solar_group(self):
        """创建农历转阳历区域"""
        group_box = QGroupBox("农历转阳历")
        group_box.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        group_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #dee2e6;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 8px 0 8px;
                color: #495057;
                background-color: #ffffff;
            }
        """)
        
        layout = QGridLayout(group_box)
        layout.setSpacing(15)
        layout.setContentsMargins(25, 30, 25, 25)
        
        # 农历年份
        layout.addWidget(QLabel("农历年份:"), 0, 0)
        self.lunar_year_spin = QSpinBox()
        self.lunar_year_spin.setRange(1900, 2100)
        self.lunar_year_spin.setValue(2025)
        self.lunar_year_spin.setMinimumHeight(30)
        layout.addWidget(self.lunar_year_spin, 0, 1)
        
        # 农历月份
        layout.addWidget(QLabel("农历月份:"), 0, 2)
        self.lunar_month_spin = QSpinBox()
        self.lunar_month_spin.setRange(1, 12)
        self.lunar_month_spin.setValue(1)
        self.lunar_month_spin.setMinimumHeight(30)
        layout.addWidget(self.lunar_month_spin, 0, 3)
        
        # 农历日期
        layout.addWidget(QLabel("农历日期:"), 1, 0)
        self.lunar_day_spin = QSpinBox()
        self.lunar_day_spin.setRange(1, 30)
        self.lunar_day_spin.setValue(1)
        self.lunar_day_spin.setMinimumHeight(30)
        layout.addWidget(self.lunar_day_spin, 1, 1)
        
        # 闰月选择
        self.leap_month_check = QCheckBox("闰月")
        self.leap_month_check.setMinimumHeight(25)
        layout.addWidget(self.leap_month_check, 1, 2)
        
        # 转换按钮
        lunar_convert_btn = QPushButton("转换为阳历")
        lunar_convert_btn.setMinimumHeight(35)
        lunar_convert_btn.setStyleSheet("""
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 12px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
        """)
        lunar_convert_btn.clicked.connect(self.convert_lunar_to_solar)
        layout.addWidget(lunar_convert_btn, 1, 3)
        
        return group_box
    
    def create_result_group(self):
        """创建结果显示区域"""
        group_box = QGroupBox("转换结果")
        group_box.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        group_box.setMinimumHeight(500)
        group_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #dee2e6;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 8px 0 8px;
                color: #495057;
                background-color: #ffffff;
            }
        """)
        
        layout = QVBoxLayout(group_box)
        layout.setContentsMargins(25, 30, 25, 25)
        layout.setSpacing(15)
        
        self.result_text = QTextEdit()
        self.result_text.setReadOnly(True)
        self.result_text.setFont(QFont("Microsoft YaHei", 11))
        self.result_text.setMinimumHeight(380)
        self.result_text.setStyleSheet("""
            QTextEdit {
                background-color: #f8f9fa;
                border: 2px solid #e9ecef;
                border-radius: 8px;
                padding: 15px;
                line-height: 1.6;
                color: #495057;
            }
            QTextEdit:focus {
                border-color: #007bff;
                background-color: #ffffff;
            }
        """)
        self.result_text.setPlaceholderText("转换结果将在这里显示...\n\n💡 提示：\n• 选择阳历日期进行农历转换\n• 或输入农历日期进行阳历转换\n• 支持闰月计算")
        
        # 复制按钮
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        copy_btn = QPushButton("复制结果")
        copy_btn.setMinimumHeight(35)
        copy_btn.setStyleSheet("""
            QPushButton {
                background-color: #17a2b8;
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 12px;
                padding: 8px 16px;
            }
            QPushButton:hover {
                background-color: #117a8b;
            }
        """)
        copy_btn.clicked.connect(self.copy_result)
        button_layout.addWidget(copy_btn)
        
        layout.addWidget(self.result_text)
        layout.addLayout(button_layout)
        
        return group_box
    
    def convert_solar_to_lunar(self):
        """阳历转农历"""
        try:
            solar_date = self.solar_date_edit.date().toPyDate()
            result = self.lunar_calendar.solar_to_lunar(solar_date)
            
            if result['success']:
                result_text = f"""
═══════════════════════════════════════
🌙 阳历转农历结果
═══════════════════════════════════════

📅 阳历日期: {result['solar_date'].strftime('%Y年%m月%d日')}
🌙 农历日期: {result['formatted']}
📝 简化格式: {result['simple_format']}

📊 详细信息:
• 农历年份: {result['lunar_year']}年
• 农历月份: {result['month_name']}
• 农历日期: {result['day_name']}
• 是否闰月: {'是' if result['is_leap_month'] else '否'}
• 生肖属相: {result['zodiac']}
• 天干地支: {result['ganzhi']}

🎊 传统信息:
• 干支年份: {result['ganzhi']}年
• 生肖年份: {result['zodiac']}年
                """
            else:
                result_text = f"""
═══════════════════════════════════════
❌ 转换失败
═══════════════════════════════════════

阳历日期: {result['solar_date'].strftime('%Y年%m月%d日')}
错误信息: {result.get('error', '未知错误')}

💡 提示:
可能需要安装zhdate库来支持农历转换功能。
请运行: pip install zhdate
                """
            
            self.result_text.setPlainText(result_text.strip())
            
            # 添加到历史记录
            if self.history_manager and result['success']:
                input_data = {
                    'solar_date': str(solar_date),
                    'conversion_type': '阳历转农历'
                }
                self.history_manager.add_calculation_record("阳历转农历", input_data, result)
            
        except Exception as e:
            QMessageBox.critical(self, "转换错误", f"阳历转农历过程中出现错误:\n{str(e)}")
    
    def convert_lunar_to_solar(self):
        """农历转阳历"""
        try:
            lunar_year = self.lunar_year_spin.value()
            lunar_month = self.lunar_month_spin.value()
            lunar_day = self.lunar_day_spin.value()
            is_leap_month = self.leap_month_check.isChecked()
            
            result = self.lunar_calendar.lunar_to_solar(lunar_year, lunar_month, lunar_day, is_leap_month)
            
            if result['success']:
                result_text = f"""
═══════════════════════════════════════
☀️ 农历转阳历结果
═══════════════════════════════════════

🌙 农历日期: {result['lunar_formatted']}
📅 阳历日期: {result['solar_formatted']}

📊 详细信息:
• 阳历: {result['solar_date'].strftime('%Y年%m月%d日')} ({result['solar_date'].strftime('%A')})
• 农历: {result['lunar_year']}年{result['month_name']}{result['day_name']}
• 是否闰月: {'是' if result['is_leap_month'] else '否'}
• 生肖属相: {result['zodiac']}
• 天干地支: {result['ganzhi']}

🎊 传统信息:
• 干支年份: {result['ganzhi']}年
• 生肖年份: {result['zodiac']}年
                """
            else:
                result_text = f"""
═══════════════════════════════════════
❌ 转换失败
═══════════════════════════════════════

农历日期: {lunar_year}年{lunar_month}月{lunar_day}日{'（闰月）' if is_leap_month else ''}
错误信息: {result.get('error', '未知错误')}

💡 提示:
可能需要安装zhdate库来支持农历转换功能。
请运行: pip install zhdate
                """
            
            self.result_text.setPlainText(result_text.strip())
            
            # 添加到历史记录
            if self.history_manager and result['success']:
                input_data = {
                    'lunar_year': lunar_year,
                    'lunar_month': lunar_month,
                    'lunar_day': lunar_day,
                    'is_leap_month': is_leap_month,
                    'conversion_type': '农历转阳历'
                }
                self.history_manager.add_calculation_record("农历转阳历", input_data, result)
            
        except Exception as e:
            QMessageBox.critical(self, "转换错误", f"农历转阳历过程中出现错误:\n{str(e)}")
    
    def copy_result(self):
        """复制结果到剪贴板"""
        result_text = self.result_text.toPlainText()
        if result_text:
            clipboard = QApplication.clipboard()
            clipboard.setText(result_text)
            
            # 创建一个浮动的成功提示
            self.show_floating_tip("✅ 复制成功！", "#28a745")
            
        else:
            # 没有结果时弹窗提醒
            QMessageBox.warning(self, "提示", "⚠️ 没有可复制的结果\n\n请先进行转换后再复制结果。")
    
    def show_floating_tip(self, message, color):
        """显示浮动提示"""
        from PyQt5.QtCore import QTimer
        from PyQt5.QtWidgets import QFrame
        
        # 创建卡片式提示框
        tip_frame = QFrame(self)
        tip_frame.setFrameStyle(QFrame.NoFrame)
        
        # 使用淡绿色背景
        tip_frame.setStyleSheet("""
            QFrame {
                background-color: rgba(212, 237, 218, 0.95);
                border: 1px solid rgba(40, 167, 69, 0.3);
                border-radius: 12px;
            }
        """)
        
        # 创建布局
        layout = QHBoxLayout(tip_frame)
        layout.setContentsMargins(16, 12, 16, 12)
        layout.setSpacing(12)
        
        # 创建圆形图标
        icon_label = QLabel("✓", tip_frame)
        icon_label.setStyleSheet("""
            QLabel {
                background-color: #28a745;
                color: white;
                border-radius: 15px;
                font-size: 14px;
                font-weight: bold;
                min-width: 30px;
                max-width: 30px;
                min-height: 30px;
                max-height: 30px;
            }
        """)
        icon_label.setAlignment(Qt.AlignCenter)
        
        # 创建文字标签
        text_label = QLabel("复制成功", tip_frame)
        text_label.setStyleSheet("""
            QLabel {
                color: #155724;
                font-size: 14px;
                font-weight: bold;
                background: transparent;
                border: none;
            }
        """)
        
        layout.addWidget(icon_label)
        layout.addWidget(text_label)
        
        # 调整框架大小
        tip_frame.adjustSize()
        tip_frame.setFixedSize(tip_frame.sizeHint())
        
        # 定位在应用的上半部分中央
        parent_rect = self.rect()
        tip_x = (parent_rect.width() - tip_frame.width()) // 2
        tip_y = parent_rect.height() // 5  # 放在上1/5位置
        tip_frame.move(tip_x, tip_y)
        
        # 显示提示框
        tip_frame.show()
        tip_frame.raise_()  # 确保在最顶层
        
        # 2秒后自动消失
        QTimer.singleShot(2000, tip_frame.deleteLater)
    
    def clear_inputs(self):
        """清空输入"""
        self.result_text.clear()
    
    def copy_result(self):
        """复制结果"""
        pass
    
    def clear_all(self):
        """清空所有内容"""
        self.clear_inputs()
